package com.demo.minademo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private EditText mInput;
    private Button mSend;
    private TextView mResponse;

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String msg = intent.getStringExtra(DefaultHandler.MSG);
            mResponse.setText(msg);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mInput = findViewById(R.id.et);
        mSend = findViewById(R.id.send);
        mResponse = findViewById(R.id.response);

        mSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = mInput.getText().toString();
                if(!TextUtils.isEmpty(msg)) {
                    SessionManager.getInstance().writeToService(msg);
                }
            }
        });
        initReceiver();
        startService();
    }

    private void initReceiver(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(DefaultHandler.BROADCAST_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,filter);
    }


    private void startService(){
        Intent intent = new Intent(this,MinaService.class);
        startService(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Intent intent = new Intent(this,MinaService.class);
        startService(intent);

        if(mReceiver != null){
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
        }
    }
}
